package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.MemberInfoListMapper;
import cc.rengu.igas.momp.common.dao.impl.MemberInfoListMapperImpl;
import cc.rengu.igas.momp.common.entity.TMMemberInfo;
import cc.rengu.igas.momp.common.entity.TMCouponInfo;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.bean.MemberCouponInfoBean;
import cc.rengu.igas.momp.facade.request.QueryMemberCouponInfoRequest;
import cc.rengu.igas.momp.facade.response.QueryMemberCouponInfoResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liujinan
 * @version 1.0.0
 * @date 2020/3/31
 * @Description: 会员卡券信息查询功能实现
 */
public class MemberCouponQueryService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {
            QueryMemberCouponInfoRequest queryMemberCouponInfoRequest = new QueryMemberCouponInfoRequest();
            ConvertUtil.convertOutput(queryMemberCouponInfoRequest);

            QueryMemberCouponInfoResponse queryMemberCouponInfoResponse = new QueryMemberCouponInfoResponse();
            queryMemberCouponInfoResponse.setHeader(queryMemberCouponInfoRequest.getHeader());
            BizResponse<QueryMemberCouponInfoResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryMemberCouponInfoResponse);

            // 服务调用
            BizResponse<QueryMemberCouponInfoResponse> bizResponseNew = memberCouponQuery(xmlTreeUtil, queryMemberCouponInfoRequest, queryMemberCouponInfoResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }

    private BizResponse<QueryMemberCouponInfoResponse> memberCouponQuery(XmlTreeUtil xmlTreeUtil, QueryMemberCouponInfoRequest queryMemberCouponInfoRequest, QueryMemberCouponInfoResponse queryMemberCouponInfoResponse) throws Exception {

        BizResponse<QueryMemberCouponInfoResponse> bizResponse = new BizResponse<>();
        rglog.debug("TXN_NUM = {}", queryMemberCouponInfoRequest.getHeader().getTxnNum());

        // 查询会员信息表数据
        TMMemberInfo tmMemberInfo = getMemberInfo(queryMemberCouponInfoRequest);
        if (null == tmMemberInfo) {
            rglog.error("根据查询条件查询会员信息失败!");
            throw new BizException(RespCodeEnum.GET_MEMBERINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERINFO_ERROR.getRespDesc());
        }

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(Integer.parseInt(queryMemberCouponInfoRequest.getPageIndex()));
        pageInfo.setPageSize(Integer.parseInt(queryMemberCouponInfoRequest.getPageSize()));
        PageResult pageResult;
        // 查询会员卡券信息数据
        pageResult = getAllMemberCouponListInfo(queryMemberCouponInfoRequest, pageInfo);

        if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
            rglog.error("根据查询条件查询会员卡券信息失败!");
            throw new BizException(RespCodeEnum.GET_MEMBERINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERINFO_ERROR.getRespDesc());
        }

        List<TMCouponInfo> couponInfoList = new ArrayList<>();
        if (pageResult.getResult().isEmpty()) {
            rglog.info("根据查询条件查询到0条会员卡券信息!");
            queryMemberCouponInfoResponse.setTotalPage(CommonConstant.ZERO_COMMON_CONSTANT);
            queryMemberCouponInfoResponse.setTotalRows(CommonConstant.ZERO_COMMON_CONSTANT);

        } else {
            for (Object object : pageResult.getResult()) {
                couponInfoList.add((TMCouponInfo) object);
            }

            rglog.info("SIZE=<{}>", pageResult.getResult().size());

            List<MemberCouponInfoBean> memberCouponInfoBeanList = couponInfoList.stream().map(this::convertMemberCouponInfo).collect(Collectors.toList());
            queryMemberCouponInfoResponse.setCouponInfoList(memberCouponInfoBeanList);

            queryMemberCouponInfoResponse.setTotalPage(Integer.toString(pageResult.getPageInfo().getTotalPage()));
            queryMemberCouponInfoResponse.setTotalRows(Integer.toString(pageResult.getPageInfo().getTotalRows()));
        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryMemberCouponInfoResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryMemberCouponInfoResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(queryMemberCouponInfoResponse);

        return bizResponse;
    }

    /**
     * @param queryMemberCouponInfoRequest
     * @param memberInfoList
     * @param queryClause
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/31
     * @Description: 会员信息查询
     */
    private TMMemberInfo getMemberInfo(QueryMemberCouponInfoRequest queryMemberCouponInfoRequest) {

        try {
            String queryType = queryMemberCouponInfoRequest.getQueryType();
            rglog.info("查询类型queryType：" + queryType);
            MemberInfoListMapper membInfoListMapper = new MemberInfoListMapperImpl();
            //进行会员信息数据查询
            TMMemberInfo tmMemberInfo = membInfoListMapper.selectMemberInfoByPK(queryMemberCouponInfoRequest.getHeader().getInstId(),
                    queryMemberCouponInfoRequest.getMemberId());

            return tmMemberInfo;

        } catch (Exception e) {
            rglog.error("根据查询条件查询会员信息失败!");
            throw new BizException(RespCodeEnum.GET_MEMBERINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERINFO_ERROR.getRespDesc());
        }
    }

    /**
     * @param moneyOffMcListRequest
     * @param couponInfoList
     * @return void
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/31
     * @Description: 查询会员卡券信息
     */
    private PageResult getAllMemberCouponListInfo(QueryMemberCouponInfoRequest queryMemberCouponInfoRequest, PageInfo pageInfo) {

        String queryClause = "instId:" + queryMemberCouponInfoRequest.getHeader().getInstId() + "memberId" + queryMemberCouponInfoRequest.getMemberId()
                + "couponStatus:" + queryMemberCouponInfoRequest.getCouponStatus();

        try {
            MemberInfoListMapper memberInfoListMapper = new MemberInfoListMapperImpl();
            PageResult pageResult = memberInfoListMapper.selectMemberCouponInfo(queryMemberCouponInfoRequest.getHeader().getInstId(),
                    queryMemberCouponInfoRequest.getMemberId(),
                    queryMemberCouponInfoRequest.getCouponStatus(), pageInfo);

            return pageResult;
        } catch (Exception e) {
            rglog.error("根据查询条件<{}>会员卡券列表信息失败!", queryClause);
            throw new BizException(RespCodeEnum.GET_MONEY_OFF_MC_LIST_ERROR.getRespCode(), RespCodeEnum.GET_MONEY_OFF_MC_LIST_ERROR.getRespDesc());
        }
    }

    /**
     * @param couponInfo
     * @return cc.rengu.igas.momp.facade.bean.MemberCouponInfo
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/31
     * @Description: 数据库实体类和接口实体类数据转换
     */
    private MemberCouponInfoBean convertMemberCouponInfo(TMCouponInfo couponInfo) {
        MemberCouponInfoBean memberCouponInfoBean = new MemberCouponInfoBean();
        try {
            //卡券编号
            memberCouponInfoBean.setCouponNo(couponInfo.getCouponNo());
            //卡券有效起始日期
            memberCouponInfoBean.setCouponStartDate(couponInfo.getCouponStartDate());
            //卡券有效结束日期
            memberCouponInfoBean.setCouponEndDate(couponInfo.getCouponEndDate());
            //领取日期
            memberCouponInfoBean.setClaimDate(couponInfo.getClaimDate());
            //领取时间
            memberCouponInfoBean.setClaimTime(couponInfo.getClaimTime());
            //卡券状态
            memberCouponInfoBean.setCouponStatus(couponInfo.getCouponStatus());
            //卡券可抵扣金额
            memberCouponInfoBean.setCouponAmt(couponInfo.getCouponAmt());
            //卡券领取方式
            memberCouponInfoBean.setClaimType(couponInfo.getClaimType());
            //卡券规则描述
            memberCouponInfoBean.setRuleContent(couponInfo.getRuleIndex());

        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换会员卡券信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return memberCouponInfoBean;
    }
}
